package com.zzyl.nursing.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.vo.IotMsgNotifyData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设备数据Service业务层处理
 * 
 * @author alexis
 * @date 2025-03-08
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        LambdaQueryWrapper<DeviceData> lambdaQueryWrapper =  new LambdaQueryWrapper<>();
        Page<DeviceData> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        //模糊查询设备名称
        if(StrUtil.isNotEmpty(dto.getDeviceName())){
            lambdaQueryWrapper.eq(DeviceData::getDeviceName,dto.getDeviceName());
        }
        //精确查询功能名称
        if (StrUtil.isNotEmpty(dto.getFunctionId())) {
            lambdaQueryWrapper.eq(DeviceData::getFunctionId, dto.getFunctionId());
        }
        //时间范围查询
        if(ObjUtil.isNotEmpty(dto.getStartTime()) && ObjUtil.isNotEmpty(dto.getEndTime())){
            lambdaQueryWrapper.between(DeviceData::getAlarmTime,dto.getStartTime(),dto.getEndTime());
        }

        //分页查询
        page = page(page,lambdaQueryWrapper);
        //分装结果
        TableDataInfo<DeviceData> tableData = new TableDataInfo<>();
        tableData.setCode(HttpStatus.SUCCESS);
        tableData.setMsg("查询成功");
        tableData.setRows(page.getRecords());
        tableData.setTotal(page.getTotal());
        return tableData;
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 批量保存数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId, deviceId));
        // 判断设备是否存在
        if (ObjUtil.isNull(device)) {
            throw new BaseException("设备不存在");
        }
        if (ObjUtil.isNull(iotMsgNotifyData.getBody()) || ObjUtil.isEmpty(iotMsgNotifyData.getBody().getServices())) {
            throw new BaseException("数据为空");
        }
        List<DeviceData> dataList = new ArrayList<>();
        iotMsgNotifyData.getBody().getServices().forEach(item -> {
            item.getProperties().forEach((k, v) -> {
                // 时间格式转换
                LocalDateTime alarmTime = LocalDateTimeUtil.parse(item.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
                alarmTime = alarmTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                // 构建数据
                DeviceData deviceData = DeviceData.builder()
                        .deviceName(device.getDeviceName())
                        .iotId(deviceId)
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(k)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .dataValue(v.toString())
                        .alarmTime(alarmTime)
                        .build();
                // 添加到集合
                dataList.add(deviceData);
            });
        });
        if (!saveBatch(dataList)) {
            throw new BaseException("保存失败");
        }

        try {
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, dataList);
        } catch (Exception e) {
            log.error("保存设备数据到redis失败", e);
        }
    }
}
